package com.ruleengine.admin;

import com.ruleengine.worker.model.Chain;
import com.ruleengine.worker.rulechain.ChainManager;
import com.ruleengine.worker.runner.chain.ChainRunner;
import com.ruleengine.worker.runner.chain.ChainRunnerManager;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lianghanwei on 2024/3/23
 */
@Slf4j
public class NotifyWorkerClient {

    private final ChainManager chainManager;
    private final ChainRunnerManager chainRunnerManager;

    public NotifyWorkerClient(ChainManager chainManager, ChainRunnerManager chainRunnerManager) {
        this.chainManager = chainManager;
        this.chainRunnerManager = chainRunnerManager;
    }

    public void notifyRulechainUpdated(String rulechainId) {
        ChainRunner chainRunner = chainRunnerManager.get(rulechainId);
        if (chainRunner == null) {
            log.warn("ChainRunner not found, rulechainId={}", rulechainId);
            return;
        }

        Chain chain = chainManager.getChain(rulechainId);
        if (chain == null) {
            log.error("Chain in ENABLED state not found, rulechainId={}", rulechainId);
            return;
        }

        chainRunnerManager.update(rulechainId, chain);
    }

    public void notifyRulechainDeleted(String rulechainId) {
        ChainRunner chainRunner = chainRunnerManager.get(rulechainId);
        if (chainRunner == null) {
            log.warn("ChainRunner not found, rulechainId={}", rulechainId);
            return;
        }

        chainRunnerManager.remove(rulechainId);
    }
}
